package mainUI;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.ExitAppUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.SoundUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.rey.material.app.ThemeManager;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import application.UIApplication;
import application.UIKeyValueSet;
import frame.UIActivity;
import interfaces.IReturnObject;
import interfaces.ISignalrListener;
import menhoo.com.i8officelibrary.R;
import model.DownloadDbModel;
import model.IMCvnDBModel;
import model.IMFileModel;
import model.IMMessageDBModel;
import model.LoginUser;
import model.TabModel;
import receiver.SignalrReceiver;
import service.DownLoadService;
import service.SignalrService;


public class AppActivity extends UIActivity implements OnMenuItemClickListener, OnMenuItemLongClickListener {

    //选择文件
    public static final int Open_Apps = 0x1001;

    List<String> networkStatePromptInfoKeyList = new ArrayList();

    OnMenuItemClickListener onMenuItemClickListener;
    String promptKey = null;
    Handler hander = new Handler();

    //signalr连接服务
    private SignalrService signalrService;
    private ServiceConnection signalrServiceConn;
    private SignalrReceiver signalrReceiver;
    private ISignalrListener iSignalrListener;
    private boolean isRunSignalrService=true;
    public boolean isImHint=true;

    //
    TextView textViewIMhint = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitAppUtil.getInstance().addActivity(this);
//        setImmerseStatusBar(Color.parseColor("#36b4f5"));
//        setImmerseStatusBar(Color.parseColor("#000000"));

//        if(isRunSignalrService){
//            setSignalreceiverHandle(new ISignalrListener() {
//                @Override
//                public void OnRefreshOnline(Context context, Intent intent, String count) {
////                    MessageUtil.showShortToast(AppActivity.this,"刷新用户：用户数量"+count);
//                }
//
//                @Override
//                public void OnStart(Context context, Intent intent,String connID) {
//                    AppApplication.setSignalrID(connID);
////                    MessageUtil.showShortToast(AppActivity.this,"signalr连接上了,connid="+connID);
//                }
//
//                @Override
//                public void OnStop(Context context, Intent intent) {
////                    MessageUtil.showShortToast(AppActivity.this,"signalr断开了");
//                }
//
//                @Override
//                public void HasUserOnline(Context context, Intent intent, JSONObject data) {
////                    MessageUtil.showShortToast(AppActivity.this,"signalr HasUserOnline");
//                }
//
//                @Override
//                public void HasUserOffline(Context context, Intent intent, JSONObject data) {
////                    MessageUtil.showShortToast(AppActivity.this,"signalr HasUserOffline");
//                }
//
//                @Override
//                public void OnMessage(Context context, Intent intent, JSONObject data) {
////                    MessageUtil.showShortToast(AppActivity.this,"signalr OnMessage");
//                    IMMessageDBModel model = new IMMessageDBModel(data);
//                    OnImMessage(context,model);
//                }
//
//                @Override
//                public void HasCvnUpdate(Context context, Intent intent, JSONObject data) {
////                    MessageUtil.showShortToast(AppActivity.this,"signalr HasCvnUpdate");
//                    ImHasCvnUpdate(context,data);
//                }
//            });
//            bindSignalrService();
//        }
//        setHintView(R.layout.im_hint);
        textViewIMhint=(TextView)findViewById(R.id.textViewHint);

    }
    public void setIsImHint(boolean F){
        this.isImHint = F;
    }

    Runnable hintRun = new Runnable() {
        @Override
        public void run() {
            hideHint();
        }
    };
    public void showHintText(String text){
        if(textViewIMhint!=null){
            textViewIMhint.setText(text);
            showHint();
            HandlerUtil.removeRunable(hintRun);
            HandlerUtil.runOnUiThreadDelay(hintRun,1000*2);
        }
    }
    public void ImHasCvnUpdate(Context context, JSONObject data){

    }
    public void OnImMessage(Context context,IMMessageDBModel message){
        IMMessageDBModel model = message;
        try {
            if(model.MessageType.equalsIgnoreCase("File") && model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                IMFileModel fileInfo = model.getFileInfo();
                IMMessageDBModel fItem = getDB().findById(IMMessageDBModel.class,fileInfo.ID);
                if(fItem!=null){
                    model.UID=fItem.UID;
                    model.CreateTime=fItem.CreateTime;
                    getDB().update(model);
                }
                else{
                    //播放声音
                    if (context != null && !model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)) {
                        SoundUtil.play(context);
                        VibrateUtil.vibrateLong(context);
                    }
                    getDB().save(model);
                }
            }
            else{
                //播放声音
                if (context != null && !model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)) {
                    SoundUtil.play(context);
                    VibrateUtil.vibrateLong(context);
                }
                getDB().save(model);
            }

            IMCvnDBModel cvn = getDB().findFirst(Selector.from(IMCvnDBModel.class).where("groupID","=",model.GroupID));
            if(cvn!=null){
                cvn.unreadCount+=1;
                getDB().update(cvn);
            }
            else{
//                cvn = new IMCvnDBModel();
//                cvn.groupID=model.GroupID;
//                cvn.unreadCount=1;
//                cvn.createTime = DateUtil.Now();
//                cvn.lastTime = DateUtil.Now();
//                cvn.CurrUserID=AppApplication.getUser().EmplID;
//                cvn.CurrWebSite=HttpUrlConstant.getWebSiteFullUrl("");
//                getDB().save(cvn);
            }

        } catch (Exception ex) {}

        try {
            if(isImHint){
                List<IMCvnDBModel> cvnList = getDB().findAll(Selector.from(IMCvnDBModel.class).where("unreadCount",">",0));
                if(cvnList!=null && cvnList.size()>0){
                    int i=0;
                    for(IMCvnDBModel item : cvnList){
                        i+=item.unreadCount;
                    }
                    if(i>99){
                        showHintText("99+");
                    }
                    else{
                        showHintText(i+"");
                    }

                }
            }


        }
        catch (Exception e){}

    }

    public void setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) {
        this.onMenuItemClickListener = onMenuItemClickListener;
    }

    /**
     * 显示一个简单的提示框
     *
     * @param message      提示文字
     * @param isCancelable 是否是模式弹出(点击周边是否会消失)
     */
    public void showSimpleDialogMessage(String message, boolean isCancelable) {
        showSimpleDialogMessage(message, null, isCancelable, false);
    }

    /**
     * 显示一个简单的提示框
     *
     * @param message      提示文字
     * @param returnObject 点击确定按钮之后的回调函数
     * @param isCancelable 是否是模式弹出(点击周边是否会消失)
     * @param isCancelBtn  是否显示取消按钮
     */
    public void showSimpleDialogMessage(String message, final IReturnObject returnObject, boolean isCancelable, boolean
            isCancelBtn) {
        try {
            StringBuilder sb = new StringBuilder();
            if (message.length() < 40) {
                int _len = (40 - message.length()) / 2;

                for (int i = 0; i < _len; i++) {
                    sb.append(" ");
                }
                sb.append(message);
                for (int i = 0; i < _len; i++) {
                    sb.append(" ");
                }
            } else {
                sb.append(message);
            }

            boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
            Dialog.Builder builder = new SimpleDialog.Builder(isLightTheme ? R.style.SimpleDialogLight : R.style.SimpleDialog) {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    super.onPositiveActionClicked(fragment);
                    if (returnObject != null)
                        returnObject.returnResult(null);
                }

            };

            ((SimpleDialog.Builder) builder).message(sb.toString())
                    .positiveAction("确定");
            if (isCancelBtn) {
                builder.neutralAction("取消");
            }

            DialogFragment fragment = DialogFragment.newInstance(builder);
            fragment.setCancelable(isCancelable);
            fragment.show(getSupportFragmentManager(), null);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

    }

    /**
     * 检查是否已经登陆过了,如果没有则重新登陆,再执行传递过来的参数
     *
     * @param returnObject
     */
    public void checkLogin(IReturnObject<Boolean> returnObject) {
        if (!Check.isEmpty(AppApplication.getSession())) {
            returnObject.returnResult(true);
        } else {
            //重新登陆
            LoginUser user = AppApplication.getUser();
            try {
                //设置网站默认地址
                HttpUrlConstant.setWebSite(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIPUrl));
            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
            }

            if (user != null) {
                Login(user.userName, user.pwd, returnObject);
            }
        }

    }

    /**
     * 登陆
     *
     * @param name
     * @param pwd
     * @param returnObject
     */
    public void Login(final String name, final String pwd, final IReturnObject<Boolean> returnObject) {
        Login(name,pwd,returnObject,true);
    }
    /**
     * 登陆
     *
     * @param name
     * @param pwd
     * @param returnObject
     * @param isShowLoading
     */
    public void Login(final String name, final String pwd, final IReturnObject<Boolean> returnObject,boolean isShowLoading) {

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", name);
        params.addQueryStringParameter("pwd", pwd);

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Type", "MobileApp");
            jsonObject.put("Hardware", AndroidUtil.getUniqueID(this));
            jsonObject.put("Info", "android");
            params.addQueryStringParameter("device", jsonObject.toString());
        } catch (Exception ex) {
        }

        params.addQueryStringParameter("persistent", "true");
        httpHelp(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.Login), params, new RequestCallBack() {

            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                if (responseInfo.result != null) {
                    //登陆成功
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        if (jsonObject.getBoolean("Succeed")) {

                            AppApplication.setSession(jsonObject.getString("Message"));
                            JSONObject jsonData = jsonObject.getJSONObject("Data");
                            JSONArray NavbarArray = jsonData.isNull("Navbar") ? null : jsonData.getJSONArray("Navbar");

                            LoginUser user = new LoginUser();
                            user.userName = name;
                            user.pwd = pwd;
                            user.EmplID = jsonData.getString("ID");
                            user.EmplName = jsonData.getString("Name");
                            user.ProductID = jsonData.getString("ProductID");
                            user.ProductName = jsonData.getString("ProductName");
                            user.DeptAndPos = jsonData.getString("DeptAndPos");
                            user.Image = jsonData.getString("Image");
                            user.CanInvite = jsonData.getBoolean("CanInvite");
                            user.InvitePhoneUrl=jsonData.getString("InvitePhoneUrl");
                            user.InviteWechatUrl=jsonData.getString("InviteWechatUrl");

                            if (AppApplication.getUser() != null) {
                                user.setId(AppApplication.getUser().getId());
                                user.autoLogin = AppApplication.getUser().autoLogin;

                                getDB().deleteAll(LoginUser.class);
                                getDB().save(user);
                            } else {
                                getDB().save(user);
                            }

                            AppApplication.setUser(getDB().findFirst(LoginUser.class));
                            //保存导航Navbar
//                            if (NavbarArray != null && NavbarArray.length() > 0) {
//                                //先清空数据库
//                                getDB().deleteAll(TabModel.class);
//                                for (int i = 0; i < NavbarArray.length(); i++) {
//                                    JSONObject navber = NavbarArray.getJSONObject(i);
//                                    String Code = navber.getString("Code");
//                                    String Name = navber.getString("Name");
//                                    String Type = navber.getString("Type");
//                                    String Permisson = navber.isNull("Permisson") ? "" : navber.getString("Permisson");
//                                    String Icon = navber.getString("Icon");
//                                    String Url = navber.getString("Url");
//
//                                    TabModel model = new TabModel();
//                                    model.code = Code;
//                                    model.type = Type;
//                                    model.name = Name;
//                                    model.permisson = Permisson;
//                                    model.htmlUrl = Url;
//                                    model.iconUrl = HttpUrlConstant.getWebSiteFullUrl(Icon);
//                                    model.isShow = (Check.isEmpty(Code) || Code.equalsIgnoreCase("NULL")) ? false : true;
//
//                                    //写入数据
//                                    getDB().save(model);
//                                }
//
//                            }
                            //
                            if (AppApplication.getALiYunDeviceId() == null) {
//                                MessageUtil.showLongToast(AppActivity.this, "无法与服务器建立推送连接");
                                //成功
                                if (returnObject != null)
                                    returnObject.returnResult(true);
                            } else {
                                AddDeviceToken(AppApplication.getALiYunDeviceId(), new IReturnObject() {
                                    @Override
                                    public void returnResult(Object result) {
                                        //成功
                                        if (returnObject != null)
                                            returnObject.returnResult(true);
                                    }
                                });

                            }


                        } else {
                            String Message = jsonObject.getString("Message");
                            if (Message.equals("PWD_INVALID")) {
                                MessageUtil.showShortToast(AppActivity.this, "用户名密码错误");
                            } else if (Message.equals("NO_USER")) {
                                MessageUtil.showShortToast(AppActivity.this, "此用户尚未注册");
                            }
                            if (returnObject != null)
                                returnObject.returnResult(false);
                        }

                    } catch (Exception e) {
                        MessageUtil.showShortToast(AppActivity.this, "无法登陆,请联系网站管理员");
                        if (returnObject != null)
                            returnObject.returnResult(false);
                    }
                } else {
                    if (returnObject != null)
                        returnObject.returnResult(false);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (returnObject != null)
                    returnObject.returnResult(false);
            }
        }, isShowLoading);

    }

    /*
    向服务器注册 TokenID
     */
    public void AddDeviceToken(String aliyunDeviceId,final IReturnObject returnObject){
        String deviceName ="Android:"+Build.VERSION.RELEASE+"("+Build.VERSION.SDK+")"; //"Android:"+Build.VERSION.RELEASE+"("+Build.VERSION.SDK+"),"+ Build.MODEL+","+Build.BRAND;
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("deviceId",aliyunDeviceId);
        params.addQueryStringParameter("appName",getString(R.string.app_name));
        //params.addQueryStringParameter("deviceName", AndroidUtil.printSystemInfo());
        params.addQueryStringParameter("deviceName", URLEncoder.encode(deviceName));

        httpHelp(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.AddDeviceToken), params, new RequestCallBack
                () {


            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                String result = responseInfo.result == null ? null : responseInfo.result.toString();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (!jsonObject.getBoolean("Succeed")) {
                            MessageUtil.showShortToast(AppActivity.this, "TokenID 没有成功注册到 web 失败");
                            LogUtils.e(""+jsonObject.getString("Message"));
                        }
                    } catch (Exception e) {
                        LogUtils.e("" + e.getMessage());
                    }
                }
                returnObject.returnResult("成功");
            }

            @Override
            public void onFailure(HttpException e, String s) {
                returnObject.returnResult("失败");
            }
        }, false);

    }
    public void DeleteDeviceToken(String aliyunDeviceId){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("deviceId",aliyunDeviceId);

        httpHelp(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.DeleteDeviceToken), params, new RequestCallBack
                () {


            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                String result = responseInfo.result == null ? null : responseInfo.result.toString();
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (!jsonObject.getBoolean("Succeed")) {
                            MessageUtil.showShortToast(AppActivity.this, "TokenID delete失败");
                            LogUtils.e(""+jsonObject.getString("Message"));
                        }
                    } catch (Exception e) {
                        LogUtils.e("" + e.getMessage());
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        }, false);

    }
    /**
     * session过期对话框
     */
    public void sessionOverdue() {
        loginIdIsOverdue("SESSION_INVALID");
    }

    /**
     * session过期对话框
     *
     * @param message
     */
    private void loginIdIsOverdue(String message) {
        if (message == null) {
            MessageUtil.showShortToast(this, "身份验证有问题,但是没有任何的提示信息");
        } else if (message.indexOf("SESSION_INVALID") >= 0) {
            showSimpleDialogMessage(getString(R.string.login_id_is_overdue), new IReturnObject() {
                @Override
                public void returnResult(Object result) {
                    ExitAppUtil.getInstance().exitAllActivity();
                    AppApplication.openLogin(AppActivity.this);
                    //startActivity(new Intent(AppActivity.this, Login.class));
                }
            }, false, true);
        }
    }

    /**
     * 可以传递参数的Get Http请求 会进行session认证
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Get(final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    if (params != null) {
                        params.addQueryStringParameter("__session__", AppApplication.getSession());
                    }
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpGet(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(AppActivity.this, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * Get Http请求 会进行session认证
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Get(final String url, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    RequestParams params = new RequestParams();
                    params.addQueryStringParameter("__session__", AppApplication.getSession());
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpGet(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(AppActivity.this, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * 可以传递参数的Post Http请求 会进行session认证
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Post(final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    if (params != null) {
                        params.addQueryStringParameter("__session__", AppApplication.getSession());
                    }
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpPost(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            if (result == null) {
                                return;
                            }
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(AppActivity.this, "登陆-身份-出现问题");
                }
            }
        });

    }

    /**
     * Post Http请求 会进行session认证
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void Post(final String url, final IReturnObject<String> returnObj) {
        checkLogin(new IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean result) {
                if (result) {
                    RequestParams params = new RequestParams();
                    params.addQueryStringParameter("__session__", AppApplication.getSession());
                    final String urlF = HttpUrlConstant.getWebSiteFullUrl(url);
                    httpPost(urlF, params, new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    returnObj.returnResult(result);
                                } else {
                                    String message = jsonObject.isNull("Message") ? null : jsonObject.getString("Message");
                                    loginIdIsOverdue(message);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    });
                } else {
                    MessageUtil.showShortToast(AppActivity.this, "登陆-身份-出现问题");
                }
            }
        });

    }

    @Override
    public void onMenuItemClick(View view, int i) {
        onMenuItemClickListener.onMenuItemClick(view, i);
    }

    @Override
    public void onMenuItemLongClick(View view, int i) {

    }

    /**
     * 网络变化监控
     * @param context
     * @param intent
     * @param isWifi 是否是wifi连接 true wifi; false gprs
     * @param isNetworkAvailable 是否有网络  false 是没有
     * @param message
     */
    @Override
    public void onNetworkStateChange(Context context, Intent intent, boolean isWifi, boolean isNetworkAvailable, String message) {
        if (isNetworkAvailable) {

            clearNetworkPromptInfo();

            if (!isWifi) {
                String isTip = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.Network2G3GTipCount);
                if (isTip != null && isTip.equalsIgnoreCase("true")) {
                    return;
                }

                final DownLoadService downLoadService = getDownLoadService();
                if (downLoadService != null) {
                    final List<DownloadDbModel> list = downLoadService.getCurrDownloadingItem();
                    if (list != null) {
                        MessageUtil.showShortToast(this,""+list.size());
                        downLoadService.stopAllDownloadTask(getDB());
                        showSimpleDialogMessage("您当前已经切换为 2G/3G 网络,是否继续下载当前文件?", new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                for (DownloadDbModel item : list) {
                                    item.status = "start";
                                }
                                try {
                                    getDB().updateAll(list);
                                    if (list != null && list.size() > 0) {
                                        DownloadDbModel temp_download = list.get(0);
                                        downLoadService.download(temp_download.tag, temp_download.name, temp_download.url,
                                                temp_download.path);
                                    }

                                } catch (Exception e) {
                                    LogUtils.e(e.getMessage() + "");
                                }

                            }
                        }, false, true);
                        AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.Network2G3GTipCount, "true");
                    }
                }
//                promptInfoShow(R.drawable.ic_signal_wifi_off_white_48dp, "您当前已经切换为 2G/3G 网络,请注意网络流量", Color.parseColor
//                        ("#ffffff"), Color.parseColor("#81e024"), 1);
//                hander.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        clearNetworkPromptInfo();
//                    }
//                },2500);

            } else {
                //wifi
                AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.Network2G3GTipCount, "false");
            }

            //重连siganalr逻辑代码
//            final SignalrService signalr = getSignalrService();
//            if(signalr!=null){
//                signalr.IsConn(new IReturnObject<String>() {
//                    @Override
//                    public void returnResult(String result) {
//                        if(result.equalsIgnoreCase("true")){
//
//                        }
//                        else{
//                            signalr.StartSignalr();
//                        }
//                    }
//                });
//            }

        } else {
//            promptKey = promptInfoShow(R.drawable.ic_signal_wifi_off_white_48dp, message == null ? "当前网络已经断开" : message, Color
//                    .parseColor("#ffffff"), Color.parseColor("#FF0000"), 2);
//            networkStatePromptInfoKeyList.add(promptKey);
//            hander.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    clearNetworkPromptInfo();
//                }
//            },2500);
            MessageUtil.showShortToast(context,message == null ? "当前网络已经断开" : message);

            //网络断开siganalr逻辑代码
//            SignalrService signalr = getSignalrService();
//            if(signalr!=null){
//                signalr.StopSignalr();
//            }
        }
    }

    /**
     * 加入下载队列
     *
     * @param tag
     * @param url
     * @param saveFilePath
     * @param fileSize     55MB ,22mb
     */
    public void addDownloadQueue(final String tag, final String url, final String saveFilePath, String fileSize, final
    IReturnObject iReturnObject) {
        int maxMB = 20;
        if (!Network.isWifi(this)) {
            String onlyWifi = UIApplication.getAppKeyValueSet().readAppSetPreferences(UIKeyValueSet.IsOnlyWiFiUploadAndDownload);
            if (onlyWifi.equals("true")) {
                MessageUtil.showShortToast(this, "只能wifi下载");
                return;
            }

            try {
                float size = 0;
                if (fileSize.toLowerCase().endsWith("mb")) {
                    size = Float.parseFloat(fileSize.toLowerCase().replace("mb", ""));
                    if (size > maxMB) {
                        showSimpleDialogMessage("此文件大于" + maxMB + "MB,确定要用 2G/3G 网络下载么?", new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                addDownloadQueue(tag, url, saveFilePath, iReturnObject);
                                AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.Network2G3GTipCount, "true");
                            }
                        }, false, true);
                    } else {
                        addDownloadQueue(tag, url, saveFilePath, iReturnObject);
                    }

                } else if (fileSize.toLowerCase().endsWith("gb")) {
                    size = Float.parseFloat(fileSize.toLowerCase().replace("gb", ""));
                    size = size * 1024;
                    if (size > maxMB) {
                        showSimpleDialogMessage("此文件大于" + maxMB + "MB,确定要用 2G/3G 网络下载么?", new IReturnObject() {
                            @Override
                            public void returnResult(Object result) {
                                addDownloadQueue(tag, url, saveFilePath, iReturnObject);
                                AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.Network2G3GTipCount, "true");
                            }
                        }, false, true);
                    } else {
                        addDownloadQueue(tag, url, saveFilePath, iReturnObject);
                    }
                } else {
                    addDownloadQueue(tag, url, saveFilePath, iReturnObject);
                }
            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
                MessageUtil.showShortToast(this, "获得文件大小失败...");
            }

        } else {
            addDownloadQueue(tag, url, saveFilePath, iReturnObject);

        }

    }

    private void addDownloadQueue(final String tag, final String url, final String saveFilePath, IReturnObject iReturnObject) {
        final DownLoadService downLoadService = getDownLoadService();
        if (downLoadService != null) {
            downLoadService.addDownloadQueue(tag, url, saveFilePath);
            if (iReturnObject != null) {
                iReturnObject.returnResult(null);
            }
        }
    }

    /**
     * 停止下载任务
     *
     * @param url
     */
    public void cancelDownload(String url) {
        //停止下载
        DownLoadService downLoadService = getDownLoadService();
        if (downLoadService != null) {
            downLoadService.cancelDownload(url);
        }
    }

    private void clearNetworkPromptInfo() {
        if (networkStatePromptInfoKeyList != null && networkStatePromptInfoKeyList.size() > 0) {
            for (String key : networkStatePromptInfoKeyList) {
                if (key != null) {
                    promptInfoHide(key);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        signalrReceiver = new SignalrReceiver() {
            @Override
            public void SignalrHandle(Context context, Intent intent, String action, String data) {
                if (iSignalrListener != null) {
                    JSONObject jsonData = null;
                    try{
                        jsonData = new JSONObject(data);
                    }
                    catch (Exception ex){}
                    switch (action){
                        case "onStart":
                            iSignalrListener.OnStart(context,intent,data);
                            break;
                        case "onStop":
                            iSignalrListener.OnStop(context,intent);
                            break;
                        case "onRefreshOnline":
                            iSignalrListener.OnRefreshOnline(context,intent,data);
                            break;
                        case "hasUserOnline":
                            iSignalrListener.HasUserOnline(context,intent,jsonData);
                            break;
                        case "hasUserOffline":
                            iSignalrListener.HasUserOffline(context,intent,jsonData);
                            break;
                        case "onMessage":
                            iSignalrListener.OnMessage(context,intent,jsonData);
                            break;
                        case "hasCvnUpdate":
                            iSignalrListener.HasCvnUpdate(context,intent,jsonData);
                            break;
                    }
                }
            }
        };

        //注册
        registerReceiver(signalrReceiver,new IntentFilter(signalrReceiver.Action));
    }

    @Override
    protected void onPause() {
        super.onPause();
        //解除
        if(signalrReceiver!=null){
            unregisterReceiver(signalrReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearNetworkPromptInfo();
        unBindSignalrService();
    }

    /**
     * 绑定signalr连接服务
     */
    private void bindSignalrService(){
        this.signalrServiceConn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                try {
                    signalrService = ((SignalrService.SignalrBinder) service).getService();
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                signalrService = null;
            }
        };
        if (signalrServiceConn != null) {
            Intent it_service = new Intent(getApplicationContext(), SignalrService.class);
            bindService(it_service, signalrServiceConn, Context.BIND_AUTO_CREATE);
        }
        //

    }
    /**
     * 解除signalr服务的绑定
     */
    private void unBindSignalrService(){
        if (signalrServiceConn != null){
            unbindService(signalrServiceConn);
        }

    }
    /**
     * 设置signalr监控
     *
     * @param iSignalrListener
     */
    public void setSignalreceiverHandle(ISignalrListener iSignalrListener) {
        this.iSignalrListener = iSignalrListener;
    }

    /**
     * 得到 signalr 服务实例，可能会返回null
     * @return
     */
    public SignalrService getSignalrService() {
        return signalrService;
    }
    public boolean isRunSignalrService() {
        return isRunSignalrService;
    }

    /**
     * 设置是否运行signalr连接服务，要在super.onCreate(savedInstanceState);之前调用
     * @param runSignalrService
     */
    public void setRunSignalrService(boolean runSignalrService) {
        isRunSignalrService = runSignalrService;
    }
}
